package cn.wolfcode.shop.cloud.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class ErrorResponseFilter extends ZuulFilter {

    @Value("${error.path:/error}")
    private String errorPath;

    public ErrorResponseFilter() {
    }

    public String filterType() {
        return "error";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getThrowable() != null && !ctx.getBoolean("sendErrorFilter.ran", false);
    }

    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        response.setContentType("text/json;charset=utf8");

        Map<String,Object> map = new HashMap();
        if("true".equals(ctx.get("rateLimitExceeded"))){
            map.put("code",429);
            map.put("msg","访问过于频繁请1分钟后再试");
        }else{
            map.put("code",500);
            map.put("msg","系统故障");
        }

        try {
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(map));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //不走后续的filter
        ctx.setSendZuulResponse(false);
        return null;
    }
}
